import time
import uuid
import random
import time
import numpy as np
import pandas as pd
from datetime import datetime, timedelta
import logging
import threading
from typing import Dict, Any, Optional, List, Tuple
from collections import deque

# 导入系统配置
import sys
import os
# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from config.system_config import EXECUTION_ENGINE

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger('SmartRouter')

class Order:
    """订单类"""
    def __init__(self, symbol: str, qty: int, price: float = None, order_type: str = 'MARKET', side: str = 'BUY', algo: str = 'MARKET'):
        self.order_id = str(uuid.uuid4())[:8]
        self.symbol = symbol
        self.qty = qty
        self.price = price
        self.order_type = order_type  # MARKET, LIMIT, STOP, etc.
        self.side = side  # BUY, SELL
        self.algo = algo  # MARKET, VWAP, TWAP, etc.
        self.status = 'PENDING'
        self.filled_qty = 0
        self.remaining_qty = qty
        self.avg_fill_price = 0.0
        self.created_at = datetime.now().timestamp()
        self.updated_at = datetime.now().timestamp()
        self.execution_params = {}
        # 智能撤单相关属性
        self.orderbook_snapshot = None
        self.time_in_queue = 0
        self.cancel_probability = 0.0
        self.optimal_cancel_time = None
        self.cancel_reason = None
    
    def update_status(self, status: str, filled_qty: int = None, avg_fill_price: float = None):
        """更新订单状态"""
        self.status = status
        if filled_qty is not None:
            self.filled_qty = filled_qty
            self.remaining_qty = self.qty - filled_qty
        if avg_fill_price is not None:
            self.avg_fill_price = avg_fill_price
        self.updated_at = datetime.now().timestamp()
    
    def to_dict(self):
        """转换为字典格式"""
        return {
            'order_id': self.order_id,
            'symbol': self.symbol,
            'qty': self.qty,
            'price': self.price,
            'order_type': self.order_type,
            'side': self.side,
            'algo': self.algo,
            'status': self.status,
            'filled_qty': self.filled_qty,
            'remaining_qty': self.remaining_qty,
            'avg_fill_price': self.avg_fill_price,
            'created_at': self.created_at,
            'updated_at': self.updated_at,
            'execution_params': self.execution_params
        }

class CancelPredictor:
    """基于盘口变化预测的主动撤单算法"""
    def __init__(self, config=None):
        # 默认配置
        default_config = {
            'price_movement_threshold': 0.5,  # 价格变动超过0.5%触发撤单
            'orderbook_change_threshold': 20.0,  # 订单簿变化超过20%触发撤单
            'time_in_queue_threshold': 30.0,  # 排队时间超过30秒触发撤单
            'success_rate_target': 92.0,  # 目标撤单成功率
            'history_window_size': 100,  # 历史数据窗口大小
            'update_interval_ms': 50  # 更新间隔(毫秒)
        }
        
        # 使用传入的配置或默认配置
        self.config = config if config else default_config
        
        # 历史盘口数据缓存
        self.orderbook_history = {}
        # 历史撤单结果缓存
        self.cancel_history = deque(maxlen=self.config['history_window_size'])
        # 当前撤单成功率统计
        self.current_success_rate = 0.0
        # 模型参数
        self.model_params = {
            'price_factor': 0.3,
            'orderbook_factor': 0.4,
            'time_factor': 0.2,
            'volume_factor': 0.1
        }
        
    def update_orderbook_history(self, symbol, orderbook_data):
        """更新盘口历史数据"""
        if symbol not in self.orderbook_history:
            self.orderbook_history[symbol] = deque(maxlen=20)
        
        # 记录当前时间的盘口数据
        self.orderbook_history[symbol].append({
            'timestamp': time.time(),
            'orderbook': orderbook_data
        })
        
    def calculate_orderbook_change(self, symbol):
        """计算订单簿变化率"""
        if symbol not in self.orderbook_history or len(self.orderbook_history[symbol]) < 2:
            return 0.0
        
        # 获取最新和前一次的盘口数据
        latest = self.orderbook_history[symbol][-1]
        previous = self.orderbook_history[symbol][0]
        
        # 计算买单总量变化
        latest_bid_volume = sum(size for _, size in latest['orderbook'].get('bids', [])[:5])
        previous_bid_volume = sum(size for _, size in previous['orderbook'].get('bids', [])[:5])
        
        # 计算卖单总量变化
        latest_ask_volume = sum(size for _, size in latest['orderbook'].get('asks', [])[:5])
        previous_ask_volume = sum(size for _, size in previous['orderbook'].get('asks', [])[:5])
        
        # 计算总的变化率
        total_change = (abs(latest_bid_volume - previous_bid_volume) + 
                       abs(latest_ask_volume - previous_ask_volume)) / \
                      (previous_bid_volume + previous_ask_volume + 1e-8) * 100
        
        return total_change
        
    def predict_cancel_probability(self, order, market_data):
        """预测订单的撤单成功率和最佳撤单时机"""
        try:
            symbol = order.symbol
            current_time = time.time()
            
            # 更新盘口历史
            if 'orderbook' in market_data:
                self.update_orderbook_history(symbol, market_data['orderbook'])
            
            # 计算价格变动
            current_price = market_data.get(f'{symbol.lower()}_price', 0)
            if order.price and current_price:
                price_change = abs(current_price - order.price) / order.price * 100
            else:
                price_change = 0.0
            
            # 计算订单簿变化
            orderbook_change = self.calculate_orderbook_change(symbol)
            
            # 计算排队时间
            order.time_in_queue = current_time - order.created_at
            
            # 计算成交量变化
            current_volume = market_data.get(f'{symbol.lower()}_volume', 0)
            avg_volume = market_data.get(f'{symbol.lower()}_avg_volume', current_volume)
            volume_change = (current_volume - avg_volume) / (avg_volume + 1e-8) * 100 if avg_volume else 0
            
            # 综合计算撤单概率
            factors = {
                'price': min(1.0, price_change / self.config['price_movement_threshold']),
                'orderbook': min(1.0, orderbook_change / self.config['orderbook_change_threshold']),
                'time': min(1.0, order.time_in_queue / self.config['time_in_queue_threshold']),
                'volume': min(1.0, abs(volume_change) / 50.0)  # 成交量变化超过50%时影响较大
            }
            
            # 计算综合撤单概率
            cancel_probability = sum(factors[key] * self.model_params.get(f'{key}_factor', 0) 
                                    for key in factors)
            
            # 归一化到0-1范围
            cancel_probability = min(1.0, max(0.0, cancel_probability))
            
            # 更新订单的撤单概率
            order.cancel_probability = cancel_probability
            
            # 计算最佳撤单时机
            optimal_cancel_time = None
            if cancel_probability > 0.7:
                optimal_cancel_time = current_time
            
            order.optimal_cancel_time = optimal_cancel_time
            
            # 返回预测结果
            should_cancel = (cancel_probability > 0.7 and 
                           (price_change > self.config['price_movement_threshold'] or 
                            orderbook_change > self.config['orderbook_change_threshold'] or 
                            order.time_in_queue > self.config['time_in_queue_threshold']))
            
            return {
                'should_cancel': should_cancel,
                'cancel_probability': cancel_probability,
                'price_change': price_change,
                'orderbook_change': orderbook_change,
                'time_in_queue': order.time_in_queue,
                'optimal_cancel_time': optimal_cancel_time
            }
            
        except Exception as e:
            logger.error(f"Error predicting cancel probability: {str(e)}")
            return {
                'should_cancel': False,
                'cancel_probability': 0.0,
                'price_change': 0.0,
                'orderbook_change': 0.0,
                'time_in_queue': 0.0,
                'optimal_cancel_time': None
            }
    
    def update_cancel_result(self, success, order_info):
        """更新撤单结果，用于模型优化"""
        self.cancel_history.append({
            'timestamp': time.time(),
            'success': success,
            'order_info': order_info
        })
        
        # 更新撤单成功率统计
        if len(self.cancel_history) > 0:
            success_count = sum(1 for h in self.cancel_history if h['success'])
            self.current_success_rate = success_count / len(self.cancel_history) * 100
            
            # 根据成功率动态调整参数
            if self.current_success_rate < self.config['success_rate_target']:
                # 降低触发阈值以提高成功率
                self._adjust_model_params(increase_sensitivity=True)
            elif self.current_success_rate > self.config['success_rate_target'] + 5:
                # 提高触发阈值以减少不必要的撤单
                self._adjust_model_params(increase_sensitivity=False)
    
    def _adjust_model_params(self, increase_sensitivity=True):
        """动态调整模型参数"""
        adjustment_factor = 0.05  # 调整因子
        
        for key in self.model_params:
            if increase_sensitivity:
                # 增加参数权重以提高敏感性
                self.model_params[key] = min(1.0, self.model_params[key] + adjustment_factor)
            else:
                # 减少参数权重以降低敏感性
                self.model_params[key] = max(0.01, self.model_params[key] - adjustment_factor)
        
        logger.debug(f"Model parameters adjusted: {self.model_params}")
    
    def get_cancel_stats(self):
        """获取撤单统计信息"""
        return {
            'current_success_rate': self.current_success_rate,
            'history_count': len(self.cancel_history),
            'model_params': self.model_params,
            'config': self.config
        }

class SmartRouter:
    """智能订单路由模块，负责订单发送和路由优化"""
    def __init__(self, config=None):
        # 默认配置
        default_config = {
            'max_order_size': 1000000,  # 最大订单量
            'min_order_size': 1,         # 最小订单量
            'default_timeout_ms': 30000, # 默认订单超时时间（毫秒）
            'slippage_tolerance': 0.005, # 滑点容忍度（5%）
            'market_impact_limit': 0.01, # 市场冲击限制（1%）
            'order_split_threshold': 10000, # 订单拆分阈值
            'cancel_success_rate_target': 0.92, # 撤单成功率目标
            'execution_algorithms': ['MARKET', 'VWAP', 'TWAP', 'ICEBERG', 'POV'], # 支持的执行算法
            'debug_mode': False,
            'smart_cancel_enabled': True  # 启用智能撤单系统
        }
        
        # 合并传入的配置和默认配置
        self.config = {**default_config, **(config or {})}
        
        # 从系统配置中加载智能撤单配置
        if hasattr(EXECUTION_ENGINE, 'get') and 'smart_cancel' in EXECUTION_ENGINE:
            smart_cancel_config = EXECUTION_ENGINE['smart_cancel']
            self.config['smart_cancel_enabled'] = smart_cancel_config.get('enabled', True)
            if 'cancel_thresholds' in smart_cancel_config:
                self.smart_cancel_thresholds = smart_cancel_config['cancel_thresholds']
        
        # 交易所连接（实际应用中应该使用真实的API连接）
        self.exchanges = {}
        
        # 订单缓存
        self.active_orders = {}
        self.completed_orders = {}
        
        # 性能统计
        self.performance_stats = {
            'total_orders_sent': 0,
            'total_orders_filled': 0,
            'total_orders_partially_filled': 0,
            'total_orders_canceled': 0,
            'total_orders_rejected': 0,
            'avg_execution_time_ms': 0,
            'avg_slippage': 0,
            'cancel_success_rate': 0,
            'total_volume': 0,
            'total_value': 0,
            'smart_cancel_count': 0
        }
        
        # 准备智能撤单配置参数
        cancel_predictor_config = None
        if hasattr(self, 'smart_cancel_thresholds'):
            cancel_predictor_config = {
                'price_movement_threshold': self.smart_cancel_thresholds.get('price_movement', 0.5),
                'orderbook_change_threshold': self.smart_cancel_thresholds.get('orderbook_change', 20.0),
                'time_in_queue_threshold': self.smart_cancel_thresholds.get('time_in_queue', 30.0),
                'success_rate_target': EXECUTION_ENGINE['smart_cancel'].get('success_rate_target', 92.0),
                'history_window_size': 100,
                'update_interval_ms': 50
            }
            logger.info(f"Loaded smart cancel configuration from system config: {cancel_predictor_config}")
        
        # 撤单预测模型
        self.cancel_predictor = CancelPredictor(config=cancel_predictor_config)
        
        # 智能撤单监控线程
        self.smart_cancel_thread = None
        self.smart_cancel_running = False
        
        # 线程锁
        self.lock = threading.Lock()
        
        # 启动智能路由器
        self.start()
    
    def start(self):
        """启动智能路由器和智能撤单监控"""
        with self.lock:
            if not self.smart_cancel_running and self.config.get('smart_cancel_enabled', True):
                self.smart_cancel_running = True
                self.smart_cancel_thread = threading.Thread(target=self._monitor_smart_cancel, daemon=True)
                self.smart_cancel_thread.start()
                logger.info("Smart cancel monitor started")
    
    def stop(self):
        """停止智能路由器和智能撤单监控"""
        with self.lock:
            if self.smart_cancel_running and self.smart_cancel_thread:
                self.smart_cancel_running = False
                self.smart_cancel_thread.join(timeout=5)
                logger.info("Smart cancel monitor stopped")
    
    def connect_exchange(self, exchange_name: str, connection_params: Dict[str, Any]):
        """连接到交易所"""
        # 实际应用中，这里应该建立与交易所API的连接
        self.exchanges[exchange_name] = connection_params
        logger.info(f"Connected to exchange: {exchange_name}")
    
    def send_order(self, symbol: str, qty: int, algo: str = 'MARKET', order_type: str = 'MARKET', price: float = None, side: str = 'BUY') -> Dict[str, Any]:
        """发送订单"""
        try:
            # 检查订单参数
            if not self._validate_order_params(symbol, qty, algo):
                return {'success': False, 'error': 'Invalid order parameters'}
            
            # 订单拆分
            if qty > self.config['order_split_threshold']:
                return self._split_and_send_order(symbol, qty, algo, order_type, price, side)
            
            # 创建订单对象
            order = Order(
                symbol=symbol,
                qty=qty,
                price=price,
                order_type=order_type,
                side=side,
                algo=algo
            )
            
            # 选择执行算法
            if algo == 'MARKET':
                execution_result = self._execute_market_order(order)
            elif algo == 'VWAP':
                execution_result = self._execute_vwap_order(order)
            elif algo == 'TWAP':
                execution_result = self._execute_twap_order(order)
            elif algo == 'ICEBERG':
                execution_result = self._execute_iceberg_order(order)
            elif algo == 'POV':
                execution_result = self._execute_pov_order(order)
            else:
                return {'success': False, 'error': f'Unsupported execution algorithm: {algo}'}
            
            # 更新性能统计
            if execution_result.get('success', False):
                self._update_performance_stats(order)
            
            return execution_result
            
        except Exception as e:
            logger.error(f"Error sending order: {str(e)}")
            return {'success': False, 'error': str(e)}
    
    def _validate_order_params(self, symbol: str, qty: int, algo: str) -> bool:
        """验证订单参数"""
        # 检查股票代码
        if not symbol or not isinstance(symbol, str):
            logger.error("Invalid symbol")
            return False
            
        # 检查订单数量
        if not isinstance(qty, int) or qty < self.config['min_order_size'] or qty > self.config['max_order_size']:
            logger.error(f"Invalid quantity: {qty}")
            return False
            
        # 检查执行算法
        if algo not in self.config['execution_algorithms']:
            logger.error(f"Unsupported algorithm: {algo}")
            return False
            
        return True
    
    def _split_and_send_order(self, symbol: str, qty: int, algo: str, order_type: str, price: float, side: str) -> Dict[str, Any]:
        """拆分大订单并发送"""
        # 计算拆分份数
        split_count = max(2, qty // self.config['order_split_threshold'])
        
        # 计算每份大小（最后一份可能会有剩余）
        base_size = qty // split_count
        remainder = qty % split_count
        
        # 发送拆分后的订单
        order_ids = []
        total_filled = 0
        avg_price = 0
        
        for i in range(split_count):
            # 计算当前份的大小
            current_qty = base_size + (1 if i < remainder else 0)
            
            # 发送订单
            result = self.send_order(
                symbol=symbol,
                qty=current_qty,
                algo=algo,
                order_type=order_type,
                price=price,
                side=side
            )
            
            if not result.get('success', False):
                logger.error(f"Failed to send split order {i+1}/{split_count}")
                return {'success': False, 'error': f'Split order {i+1} failed', 'partial_results': order_ids}
            
            # 记录订单ID
            order_id = result.get('order_id')
            if order_id:
                order_ids.append(order_id)
                
                # 更新成交信息
                filled_qty = result.get('filled_qty', 0)
                fill_price = result.get('avg_fill_price', 0)
                
                if filled_qty > 0 and fill_price > 0:
                    total_filled += filled_qty
                    avg_price = (avg_price * (total_filled - filled_qty) + fill_price * filled_qty) / total_filled
            
            # 拆分订单之间的延迟（避免市场冲击）
            time.sleep(random.uniform(0.1, 0.5))
        
        return {
            'success': True,
            'order_ids': order_ids,
            'total_qty': qty,
            'filled_qty': total_filled,
            'avg_fill_price': avg_price,
            'message': f'Order split into {split_count} parts and sent successfully'
        }
    
    def _execute_market_order(self, order: Order) -> Dict[str, Any]:
        """执行市价单"""
        # 模拟订单执行（实际应用中应该调用交易所API）
        start_time = time.time()
        
        # 假设80-100%的成交率
        fill_rate = random.uniform(0.8, 1.0)
        filled_qty = int(order.qty * fill_rate)
        
        # 模拟平均成交价（市价单通常有一定滑点）
        if order.price:
            # 如果指定了价格，基于该价格模拟
            if order.side == 'BUY':
                avg_fill_price = order.price * (1 + random.uniform(0.001, 0.003))  # 买入滑点
            else:
                avg_fill_price = order.price * (1 - random.uniform(0.001, 0.003))  # 卖出滑点
        else:
            # 否则生成一个随机价格
            avg_fill_price = random.uniform(100, 200)
        
        # 更新订单状态
        if filled_qty == order.qty:
            order.update_status('FILLED', filled_qty, avg_fill_price)
        elif filled_qty > 0:
            order.update_status('PARTIALLY_FILLED', filled_qty, avg_fill_price)
        else:
            order.update_status('REJECTED')
            
        # 记录订单
        self.active_orders[order.order_id] = order
        
        # 计算执行时间
        execution_time = (time.time() - start_time) * 1000
        
        return {
            'success': order.status in ['FILLED', 'PARTIALLY_FILLED'],
            'order_id': order.order_id,
            'status': order.status,
            'filled_qty': filled_qty,
            'remaining_qty': order.remaining_qty,
            'avg_fill_price': avg_fill_price,
            'execution_time_ms': execution_time
        }
    
    def _execute_vwap_order(self, order: Order) -> Dict[str, Any]:
        """执行VWAP（成交量加权平均价）订单"""
        # VWAP策略：在一段时间内根据成交量分布执行订单
        start_time = time.time()
        
        # 设置VWAP执行参数
        execution_window_minutes = order.execution_params.get('execution_window_minutes', 5)
        order.execution_params['execution_window_minutes'] = execution_window_minutes
        
        # 模拟VWAP执行
        # 实际应用中，应该根据实时成交量分布动态调整下单节奏
        
        # 模拟分10个时间段执行
        intervals = 10
        interval_time = (execution_window_minutes * 60) / intervals  # 秒
        
        total_filled = 0
        total_value = 0
        
        for i in range(intervals):
            # 模拟每个时间段的成交量权重（通常中间时间段成交量较大）
            if 3 <= i <= 7:
                weight = random.uniform(0.12, 0.15)
            else:
                weight = random.uniform(0.05, 0.1)
            
            # 计算该时间段的下单量
            interval_qty = int(order.qty * weight)
            
            # 模拟价格（随时间变化）
            if order.price:
                price_change = random.uniform(-0.001, 0.001) * i  # 模拟价格随时间变化
                current_price = order.price * (1 + price_change)
            else:
                current_price = random.uniform(100, 200)
            
            # 模拟成交
            filled = interval_qty  # 假设全部成交
            total_filled += filled
            total_value += filled * current_price
            
            # 记录部分成交信息
            order.update_status('PARTIALLY_FILLED', total_filled, total_value / total_filled)
            
            # 等待下一个时间段
            if self.config['debug_mode']:
                time.sleep(interval_time * 0.01)  # 调试模式下加速
            else:
                time.sleep(interval_time)
        
        # 最终订单状态
        if total_filled >= order.qty * 0.95:  # 95%以上视为完全成交
            order.update_status('FILLED', total_filled, total_value / total_filled)
        else:
            order.update_status('PARTIALLY_FILLED', total_filled, total_value / total_filled)
        
        # 记录订单
        self.active_orders[order.order_id] = order
        
        # 计算执行时间
        execution_time = (time.time() - start_time) * 1000
        
        return {
            'success': True,
            'order_id': order.order_id,
            'status': order.status,
            'filled_qty': total_filled,
            'remaining_qty': order.remaining_qty,
            'avg_fill_price': total_value / total_filled if total_filled > 0 else 0,
            'execution_time_ms': execution_time,
            'algorithm': 'VWAP',
            'execution_window_minutes': execution_window_minutes
        }
    
    def _execute_twap_order(self, order: Order) -> Dict[str, Any]:
        """执行TWAP（时间加权平均价）订单"""
        # TWAP策略：在一段时间内均匀执行订单
        start_time = time.time()
        
        # 设置TWAP执行参数
        execution_window_minutes = order.execution_params.get('execution_window_minutes', 5)
        order.execution_params['execution_window_minutes'] = execution_window_minutes
        
        # 模拟TWAP执行
        
        # 模拟分10个时间段均匀执行
        intervals = 10
        interval_qty = order.qty // intervals
        remainder = order.qty % intervals
        interval_time = (execution_window_minutes * 60) / intervals  # 秒
        
        total_filled = 0
        total_value = 0
        
        for i in range(intervals):
            # 计算该时间段的下单量
            current_qty = interval_qty + (1 if i < remainder else 0)
            
            # 模拟价格（随时间变化）
            if order.price:
                price_change = random.uniform(-0.001, 0.001) * i  # 模拟价格随时间变化
                current_price = order.price * (1 + price_change)
            else:
                current_price = random.uniform(100, 200)
            
            # 模拟成交
            filled = current_qty  # 假设全部成交
            total_filled += filled
            total_value += filled * current_price
            
            # 记录部分成交信息
            order.update_status('PARTIALLY_FILLED', total_filled, total_value / total_filled)
            
            # 等待下一个时间段
            if self.config['debug_mode']:
                time.sleep(interval_time * 0.01)  # 调试模式下加速
            else:
                time.sleep(interval_time)
        
        # 最终订单状态
        if total_filled >= order.qty * 0.95:  # 95%以上视为完全成交
            order.update_status('FILLED', total_filled, total_value / total_filled)
        else:
            order.update_status('PARTIALLY_FILLED', total_filled, total_value / total_filled)
        
        # 记录订单
        self.active_orders[order.order_id] = order
        
        # 计算执行时间
        execution_time = (time.time() - start_time) * 1000
        
        return {
            'success': True,
            'order_id': order.order_id,
            'status': order.status,
            'filled_qty': total_filled,
            'remaining_qty': order.remaining_qty,
            'avg_fill_price': total_value / total_filled if total_filled > 0 else 0,
            'execution_time_ms': execution_time,
            'algorithm': 'TWAP',
            'execution_window_minutes': execution_window_minutes
        }
    
    def _execute_iceberg_order(self, order: Order) -> Dict[str, Any]:
        """执行冰山订单（隐藏大部分订单量）"""
        # 冰山订单：只显示部分订单量，隐藏大部分
        start_time = time.time()
        
        # 设置冰山订单参数
        display_size_ratio = order.execution_params.get('display_size_ratio', 0.1)  # 显示10%的订单量
        order.execution_params['display_size_ratio'] = display_size_ratio
        
        # 计算显示和隐藏的订单量
        display_size = max(1, int(order.qty * display_size_ratio))
        
        # 模拟冰山订单执行
        total_filled = 0
        total_value = 0
        
        # 模拟订单价格
        if not order.price:
            order.price = random.uniform(100, 200)
        
        # 模拟分多次显示小订单
        while total_filled < order.qty:
            # 计算本次显示的订单量
            current_display = min(display_size, order.qty - total_filled)
            
            # 模拟成交（可能部分成交）
            fill_rate = random.uniform(0.8, 1.0)
            filled = int(current_display * fill_rate)
            
            # 更新成交信息
            total_filled += filled
            total_value += filled * order.price
            
            # 更新订单状态
            if total_filled < order.qty:
                order.update_status('PARTIALLY_FILLED', total_filled, total_value / total_filled)
            else:
                order.update_status('FILLED', total_filled, total_value / total_filled)
                
            # 如果还有剩余量，继续显示
            if total_filled < order.qty:
                # 等待一段时间后再次显示
                time.sleep(random.uniform(0.5, 2.0))
            
            # 防止无限循环
            if time.time() - start_time > self.config['default_timeout_ms'] / 1000:
                break
        
        # 如果超时，取消剩余订单
        if total_filled < order.qty:
            order.update_status('PARTIALLY_FILLED', total_filled, total_value / total_filled if total_filled > 0 else 0)
        
        # 记录订单
        self.active_orders[order.order_id] = order
        
        # 计算执行时间
        execution_time = (time.time() - start_time) * 1000
        
        return {
            'success': True,
            'order_id': order.order_id,
            'status': order.status,
            'filled_qty': total_filled,
            'remaining_qty': order.remaining_qty,
            'avg_fill_price': total_value / total_filled if total_filled > 0 else 0,
            'execution_time_ms': execution_time,
            'algorithm': 'ICEBERG',
            'display_size_ratio': display_size_ratio
        }
    
    def _execute_pov_order(self, order: Order) -> Dict[str, Any]:
        """执行POV（成交量参与率）订单"""
        # POV策略：根据市场成交量的一定比例执行订单
        start_time = time.time()
        
        # 设置POV参数
        participation_rate = order.execution_params.get('participation_rate', 0.05)  # 参与5%的市场成交量
        order.execution_params['participation_rate'] = participation_rate
        
        # 模拟POV执行
        total_filled = 0
        total_value = 0
        
        # 模拟订单价格
        if not order.price:
            order.price = random.uniform(100, 200)
        
        # 模拟执行时间窗口（5分钟）
        end_time = start_time + 5 * 60
        
        # 模拟每分钟的市场成交量
        while time.time() < end_time and total_filled < order.qty:
            # 模拟市场成交量（随机波动）
            market_volume = random.uniform(10000, 50000)
            
            # 计算本分钟的下单量
            order_volume = market_volume * participation_rate
            current_qty = min(int(order_volume), order.qty - total_filled)
            
            # 模拟成交
            filled = current_qty  # 假设全部成交
            total_filled += filled
            total_value += filled * order.price
            
            # 更新订单状态
            if total_filled < order.qty:
                order.update_status('PARTIALLY_FILLED', total_filled, total_value / total_filled)
            else:
                order.update_status('FILLED', total_filled, total_value / total_filled)
                
            # 等待1分钟（模拟）
            if self.config['debug_mode']:
                time.sleep(0.1)  # 调试模式下加速
            else:
                time.sleep(60)
        
        # 最终订单状态
        if total_filled < order.qty:
            order.update_status('PARTIALLY_FILLED', total_filled, total_value / total_filled if total_filled > 0 else 0)
        
        # 记录订单
        self.active_orders[order.order_id] = order
        
        # 计算执行时间
        execution_time = (time.time() - start_time) * 1000
        
        return {
            'success': True,
            'order_id': order.order_id,
            'status': order.status,
            'filled_qty': total_filled,
            'remaining_qty': order.remaining_qty,
            'avg_fill_price': total_value / total_filled if total_filled > 0 else 0,
            'execution_time_ms': execution_time,
            'algorithm': 'POV',
            'participation_rate': participation_rate
        }
    
    def cancel_order(self, order_id: str, reason: str = None) -> Dict[str, Any]:
        """取消订单"""
        # 检查订单是否存在
        if order_id not in self.active_orders:
            return {'success': False, 'error': 'Order not found'}
        
        try:
            order = self.active_orders[order_id]
            
            # 使用智能撤单预测器预测成功率
            market_data = self._get_market_data(order.symbol)
            prediction = self.cancel_predictor.predict_cancel_probability(order, market_data)
            cancel_probability = prediction['cancel_probability']
            
            # 模拟撤单结果（基于预测概率）
            success = random.random() < cancel_probability
            
            if success:
                # 撤单成功
                order.update_status('CANCELED')
                order.cancel_reason = reason or 'User requested cancel'
                # 移至已完成订单
                self.completed_orders[order_id] = order
                del self.active_orders[order_id]
                
                # 更新撤单成功率统计
                self._update_cancel_success_rate(True)
                
                # 更新撤单预测器的统计信息
                self.cancel_predictor.update_cancel_result(
                    True, 
                    {'order_id': order_id, 'symbol': order.symbol, 'prediction': prediction}
                )
                
                return {
                    'success': True,
                    'order_id': order_id,
                    'status': 'CANCELED',
                    'cancel_probability': cancel_probability,
                    'reason': order.cancel_reason
                }
            else:
                # 撤单失败
                self._update_cancel_success_rate(False)
                
                # 更新撤单预测器的统计信息
                self.cancel_predictor.update_cancel_result(
                    False, 
                    {'order_id': order_id, 'symbol': order.symbol, 'prediction': prediction}
                )
                
                return {
                    'success': False,
                    'error': 'Cancel order failed',
                    'order_id': order_id,
                    'cancel_probability': cancel_probability
                }
                
        except Exception as e:
            logger.error(f"Error canceling order {order_id}: {str(e)}")
            return {'success': False, 'error': str(e)}
    
    def _predict_cancel_success(self, order: Order) -> float:
        """预测撤单成功率"""
        # 使用智能撤单预测器预测成功率
        market_data = self._get_market_data(order.symbol)
        prediction = self.cancel_predictor.predict_cancel_probability(order, market_data)
        return prediction['cancel_probability']
    
    def _update_cancel_success_rate(self, success: bool):
        """更新撤单成功率统计"""
        # 简单的统计更新逻辑
        # 实际应用中，应该使用更复杂的统计方法
        if success:
            # 撤单成功率 = (当前成功率 * 样本数 + 1) / (样本数 + 1)
            self.performance_stats['cancel_success_rate'] = (
                self.performance_stats['cancel_success_rate'] * self.performance_stats['total_orders_canceled'] + 1
            ) / (self.performance_stats['total_orders_canceled'] + 1)
        
        # 更新总撤单次数
        self.performance_stats['total_orders_canceled'] += 1
    
    def _update_performance_stats(self, order: Order):
        """更新性能统计"""
        self.performance_stats['total_orders_sent'] += 1
        
        # 更新成交量和成交额
        self.performance_stats['total_volume'] += order.filled_qty
        self.performance_stats['total_value'] += order.filled_qty * order.avg_fill_price
        
        # 更新订单状态统计
        if order.status == 'FILLED':
            self.performance_stats['total_orders_filled'] += 1
        elif order.status == 'PARTIALLY_FILLED':
            self.performance_stats['total_orders_partially_filled'] += 1
        elif order.status == 'REJECTED':
            self.performance_stats['total_orders_rejected'] += 1
        
        # 计算滑点（如果有参考价格）
        if order.price and order.avg_fill_price > 0:
            if order.side == 'BUY':
                slippage = (order.avg_fill_price - order.price) / order.price
            else:
                slippage = (order.price - order.avg_fill_price) / order.price
            
            # 更新平均滑点（指数加权移动平均）
            self.performance_stats['avg_slippage'] = (
                self.performance_stats['avg_slippage'] * 0.9 + slippage * 0.1
            )
    
    def get_order_status(self, order_id: str) -> Optional[Dict[str, Any]]:
        """获取订单状态"""
        # 检查活跃订单
        if order_id in self.active_orders:
            return self.active_orders[order_id].to_dict()
            
        # 检查已完成订单
        if order_id in self.completed_orders:
            return self.completed_orders[order_id].to_dict()
            
        return None
    
    def get_active_orders(self) -> List[Dict[str, Any]]:
        """获取所有活跃订单"""
        return [order.to_dict() for order in self.active_orders.values()]
    
    def get_performance_stats(self) -> Dict[str, Any]:
        """获取性能统计信息"""
        # 获取撤单预测器的统计信息
        cancel_stats = self.cancel_predictor.get_cancel_stats()
        
        # 更新当前撤单成功率
        self.performance_stats['cancel_success_rate'] = cancel_stats['current_success_rate']
        
        return {
            'performance': self.performance_stats.copy(),
            'cancel_predictor': cancel_stats
        }
    
    def cancel_all_orders(self, symbol: str = None) -> Dict[str, Any]:
        """取消所有订单或指定股票的所有订单"""
        canceled_orders = []
        failed_orders = []
        
        # 复制订单ID列表，避免在迭代过程中修改字典
        order_ids = list(self.active_orders.keys())
        
        for order_id in order_ids:
            order = self.active_orders[order_id]
            
            # 如果指定了股票代码，只取消该股票的订单
            if symbol and order.symbol != symbol:
                continue
                
            # 取消订单
            result = self.cancel_order(order_id, reason='Cancel all orders')
            
            if result.get('success', False):
                canceled_orders.append(order_id)
            else:
                failed_orders.append(order_id)
        
        return {
            'success': True,
            'canceled_orders': canceled_orders,
            'failed_orders': failed_orders,
            'total_canceled': len(canceled_orders),
            'total_failed': len(failed_orders)
        }
    
    def _monitor_smart_cancel(self):
        """监控订单并执行智能撤单"""
        while self.smart_cancel_running:
            try:
                # 检查活跃订单
                with self.lock:
                    active_orders_copy = list(self.active_orders.values())
                
                for order in active_orders_copy:
                    # 只处理已提交且未完全填充的订单
                    if order.status not in ['SUBMITTED', 'PARTIALLY_FILLED']:
                        continue
                    
                    try:
                        # 获取市场数据
                        market_data = self._get_market_data(order.symbol)
                        
                        # 预测撤单概率
                        prediction = self.cancel_predictor.predict_cancel_probability(order, market_data)
                        
                        # 根据预测结果执行智能撤单
                        if prediction['should_cancel']:
                            logger.info(f"Smart cancel triggered for order {order.order_id}: probability={prediction['cancel_probability']:.2f}")
                            
                            # 执行撤单
                            cancel_result = self.cancel_order(order.order_id, reason='Smart Cancel Triggered')
                            
                            # 更新性能统计
                            if cancel_result['success']:
                                self.performance_stats['smart_cancel_count'] += 1
                                
                    except Exception as e:
                        logger.error(f"Error in smart cancel monitoring for order {order.order_id}: {str(e)}")
                
                # 短暂休眠以避免CPU占用过高
                time.sleep(0.05)  # 50ms检查一次
                
            except Exception as e:
                logger.error(f"Error in smart cancel monitoring loop: {str(e)}")
                time.sleep(0.1)
    
    def _get_market_data(self, symbol: str) -> Dict[str, Any]:
        """获取市场数据"""
        # 实际应用中，这里应该从市场数据服务获取实时数据
        # 这里简化处理，返回模拟数据
        return {
            f'{symbol.lower()}_price': random.uniform(90, 110),
            f'{symbol.lower()}_volume': random.randint(100000, 1000000),
            f'{symbol.lower()}_avg_volume': random.randint(100000, 1000000),
            'orderbook': {
                'bids': [(random.uniform(99, 100), random.randint(1000, 10000)) for _ in range(5)],
                'asks': [(random.uniform(100, 101), random.randint(1000, 10000)) for _ in range(5)]
            }
        }
    
    def _update_order_from_market_data(self, order: Order):
        """根据市场数据更新订单"""
        # 实际应用中，这里应该根据实时市场数据更新订单状态
        # 这里简化处理，更新订单簿快照
        market_data = self._get_market_data(order.symbol)
        if 'orderbook' in market_data:
            order.orderbook_snapshot = market_data['orderbook']

# 示例使用
if __name__ == "__main__":
    # 初始化智能路由器
    router = SmartRouter()
    
    # 连接到交易所（模拟）
    router.connect_exchange("shanghai", {"api_key": "test_key"})
    
    # 发送测试订单 - 限价单
    order_result = router.send_order(
        symbol="600000",
        qty=1000,
        price=10.0,
        order_type="LIMIT",
        side="BUY",
        algo="MARKET"
    )
    
    print(f"发送限价单结果: {order_result}")
    
    if order_result.get('success'):
        order_id = order_result['order_id']
        
        # 模拟等待一段时间，让智能撤单监控有机会工作
        print("等待5秒，让智能撤单监控有机会分析订单...")
        time.sleep(5)
        
        # 查看活跃订单
        active_orders = router.get_active_orders()
        print(f"活跃订单: {active_orders}")
        
        # 手动触发撤单
        if order_id in [order['order_id'] for order in active_orders]:
            cancel_result = router.cancel_order(order_id, reason="Test cancellation")
            print(f"手动撤单结果: {cancel_result}")
        
    # 发送VWAP算法订单
    vwap_result = router.send_order(
        symbol="600036",
        qty=5000,
        order_type="MARKET",
        side="BUY",
        algo="VWAP",
        execution_params={"duration_min": 30}
    )
    
    print(f"发送VWAP订单结果: {vwap_result}")
    
    # 发送TWAP算法订单
    twap_result = router.send_order(
        symbol="600519",
        qty=2000,
        order_type="MARKET",
        side="BUY",
        algo="TWAP",
        execution_params={"duration_min": 15, "slice_count": 10}
    )
    
    print(f"发送TWAP订单结果: {twap_result}")
    
    # 获取性能统计
    stats = router.get_performance_stats()
    print(f"性能统计: {stats}")
    
    # 停止智能路由器
    router.stop()